const my_cookie = (() => {
  // 1 设置cookie
  function setCookie(name, value, days, path, domain, secure) {
    // 声明一个保存cookie的字符串
    let strCookie = ''
    if (name) {
      strCookie += `${name}=${value};`
    }
    // 设置cookie的过期时间,以天为单位
    if (typeof days === 'number') {
      let date = new Date()
      date.setDate(date.getDate() + days)
      strCookie += `expires=${date};`
    }
    // 设置路径
    if (path) {
      strCookie += `path=${path};`
    }
    // 设置域名
    if (domain) {
      strCookie += `domain=${domain};`
    }
    // 设置安全
    if (secure) {
      strCookie += `secure=${secure};`
    }
    document.cookie = strCookie
  }

  // 2 获得所有的cookie信息
  function getCookieAll() {
    let str = document.cookie
    let arr = []
    if (str) {
      arr = str.split('; ')
    }
    let object = {}
    arr.forEach((item) => {
      let list = item.split('=') // [a,b]
      object[list[0]] = list[1]
    })
    return object
  }

  // 3 根据名称获得cookie值
  function getCookieByName(args) {
    return getCookieAll()[args]
  }

  // 4 指定名称删除cookie
  function removeCookie(args) {
    setCookie(args, '', -1)
  }

  return { setCookie, getCookieAll, getCookieByName, removeCookie }
})()

console.log('--------------setCookie------------')
my_cookie.setCookie('name', 'oeschger')
my_cookie.setCookie('gender', '1')
my_cookie.setCookie('favorite_food', 'tripe')
console.log('--------------getCookieAll------------')
let cookies = my_cookie.getCookieAll()
console.log(cookies)
console.log('--------------getCookieByName------------')
let gender = my_cookie.getCookieByName('gender')
console.log('gender=', gender)
console.log('--------------removeCookie------------')
my_cookie.removeCookie('gender')
gender = my_cookie.getCookieByName('gender')
console.log('gender=', gender)
